public class KthSmallest {
    // leetcode 二叉搜索树中第k小的元素
    // https://leetcode.cn/problems/kth-smallest-element-in-a-bst/description/?envType=study-plan-v2&envId=top-100-liked
    // 同样因为是二叉搜索树，所以进行中序遍历
    private int count;
    public int kthSmallest(TreeNode root, int k) {
        count = k;
        return kthSmallestChild(root);
    }

    private int kthSmallestChild(TreeNode root) {
        if(root == null) return -1;
        int leftJudge = kthSmallestChild(root.left);
        if (leftJudge != -1) return leftJudge;
        count--;
        if (count == 0) return root.val;
        return kthSmallestChild(root.right);
    }
}
